# encoding=utf-8
import time
from LBT.GeneralOperation.ModuleOperation import moduleOper
from LBT.Resource.SmsAtt import SmsAtt
from LBT.Resource.BaseAtt import BaseAtt
from Parents.Functions.GeneralFunction import GeneralFunction


class smsoperation(SmsAtt, BaseAtt, GeneralFunction):
    '''
    短信模块操作功能
    '''

    def __init__(self, dr):
        self.dr = dr
        self.moduopr = moduleOper(dr)

    def studentSendSms(self, oprer, isTiming):
        """
        向第一个学生发送指定内容短信
        :param oldtext:原有内容
        :param isTiming:是否定时
        :return:元组（发送内容，学生姓名）
        """
        dr = self.dr
        # 进入模块
        isin = self.moduopr.openMoudleAndIn(self.smsNavigation_class, self.smsModule_url)
        oprer.assertTrue(isin)
        # 选择学生
        studentname = self.chioceUser(self.sms_switch_stu_id)
        # 判断如果没有有订购的学生，就终止程序。
        oprer.assertTrue(studentname != '')
        testT = dr.find_element_by_id(self.sms_select_userArea).text
        oprer.assertIn(studentname, testT)
        oldtext = self.smsTemplate(dr)
        if isTiming:
            dr.find_elements_by_name(self.sms_timing_name)[1].click()
            dr.find_element_by_id(self.sms_timing_id).send_keys(oprer.getTimintInfo())
            dr.find_element_by_class_name(self.sms_timing_btn).click()
            smsInfo = self.writeContent('向' + studentname + '家长发定时短信，时间为：', oldtext)
        else:
            smsInfo = self.writeContent('向' + studentname + '家长发及时短信，时间为：', oldtext)
        return (smsInfo, studentname)

    def smsTemplate(self, dr):
        # 选择短信模板，然后选择节日祝福里面第一条
        dr.find_element_by_css_selector(self.sms_smsTemplate_class).click()
        dr.switch_to.frame(dr.find_element_by_xpath(self.sms_smsTemplate_frame_xpath))
        dr.find_elements_by_xpath(self.sms_smsTemplate_zhufu_xpath)[4].click()
        smsInfo = dr.find_elements_by_css_selector(self.sms_smsTemplate_zhufu_content_text_class)[0].text
        dr.find_elements_by_css_selector(self.sms_smsTemplate_zhufu_content_class)[0].click()
        # 填写短信内容
        dr.switch_to.default_content()
        dr.switch_to.frame(dr.find_element_by_xpath(self.sms_sendSmsFrame))
        return smsInfo

    def chioceUser(self, attForName):
        '''选择学生/老师并返回学生/老师姓名'''
        # 选择学生
        self.dr.find_element_by_id(self.sms_select_userArea).click()
        '''修改页面元素属性---！！！'''
        js2 = "document.getElementById('layui-layer1').setAttribute('style','z-index: 19891015; width: 697px; height: 600px; top: -100px; left: 230px;')"
        self.dr.execute_script(js2)
        # 进入选择学生的frame
        self.dr.switch_to.frame(self.sms_frame_choice_stu)
        listBan = self.dr.find_elements_by_css_selector(self.sms_choice_stu_class_class)
        # 遍历每一个班级
        for itemBan in listBan:
            # 打开当前班级
            studentIsDis = False
            while not studentIsDis:
                itemBan.click()
                studentIsDis = itemBan.find_element_by_css_selector(self.sms_dept_class_iscollapse).is_displayed()
            # 拿到所有该班级所有学生信息
            studentlist = itemBan.find_elements_by_name(attForName)
            studentname = ''
            # 遍历学生，找到订购的和手机号在允许接收的范围的
            for student in studentlist:
                if student.is_enabled():
                    dataphone = str(student.get_attribute(self.sms_phone_att))
                    phoneInfos = dataphone.split(",")
                    phoneInfo = phoneInfos[0]
                    phoneAndType = phoneInfo.split("_")
                    for phoneTrue in phoneAndType:
                        if ((len(phoneTrue)) == 11 and (phoneTrue in self.receiverPhoneForTest)):
                            student.click()
                            studentname = student.get_attribute(self.sms_name_att)
                            break
                # 如果找到学生就退出遍历班级学生
                if studentname != '':
                    break
            # 如果班级没有符合条件的，就关闭班级
            while studentIsDis:
                itemBan.find_element_by_class_name(self.sms_dept_class_class).click()
                studentIsDis = itemBan.find_element_by_css_selector(self.sms_dept_class_iscollapse).is_displayed()
            # 如果找到学生就退出遍历班级
            if studentname != '':
                break
        self.dr.switch_to.parent_frame()
        self.dr.find_element_by_class_name(self.sms_frame_ok_btn).click()
        return studentname

    def chioceteacher(self):
        '''选择老师并返回老师姓名，
        说明：和之前选择学生除了switchTeaId这一个不一样外，重点是切换frame及执行js顺序不一样
        这种更适用于频繁切换老师和学生页面的时候。
        '''
        # 选择老师,进入选择老师的frame
        '''修改页面元素属性---！！！'''
        js2 = "document.getElementById('layui-layer1').setAttribute('style','z-index: 19891015; width: 697px; height: 600px; top: -50px; left: 230px;')"
        self.moduopr.openNewFrame(self.dr.find_element_by_id(self.sms_select_userArea), js2)
        listDept = self.dr.find_elements_by_css_selector(self.sms_choice_tea_dept_class)
        # 遍历每一个部门
        for itemDept in listDept:
            # 打开当前部门
            teacherIsDis = False
            while not teacherIsDis:
                itemDept.click()
                teacherIsDis = itemDept.find_element_by_css_selector(self.sms_dept_class_iscollapse).is_displayed()
            # 拿到所有该班级所有老师信息
            teacherlist = itemDept.find_elements_by_name(self.sms_switch_tea_id)
            teachername = ''
            # 遍历老师，找到订购的和手机号在允许接收的范围的
            for teacher in teacherlist:
                if teacher.is_enabled():
                    dataphone = str(teacher.get_attribute(self.sms_phone_att))
                    phoneInfos = dataphone.split(",")
                    phoneInfo = phoneInfos[0]
                    phoneAndType = phoneInfo.split("_")
                    for phoneTrue in phoneAndType:
                        if ((len(phoneTrue)) == 11 and (phoneTrue in self.receiverPhoneForTest)):
                            teacher.click()
                            teachername = teacher.get_attribute(self.sms_name_att)
                            break
                # 如果找到老师就退出遍历部门老师
                if teachername != '':
                    break
            # 如果班级没有符合条件的，就关闭部门
            while studentIsDis:
                itemDept.find_element_by_class_name(self.sms_dept_class_class).click()
                studentIsDis = itemDept.find_element_by_css_selector(self.sms_dept_class_iscollapse).is_displayed()
            # 如果找到老师就退出遍历部门
            if teachername != '':
                break
        self.dr.switch_to.parent_frame()
        self.dr.find_element_by_class_name(self.sms_frame_ok_btn).click()
        return teachername

    def chioceteacherone(self, deptid, teachername):
        '''
        '''
        # 选择老师,进入选择老师的frame
        '''修改页面元素属性---！！！'''
        js2 = "document.getElementById('layui-layer1').setAttribute('style','z-index: 19891015; width: 697px; height: 600px; top: -50px; left: 230px;')"
        self.moduopr.openNewFrame(self.dr.find_element_by_id(self.sms_select_userArea), js2)
        self.dr.find_element_by_id(self.deptid).click()
        self.dr.find_element_by_xpath("//input[@data-tname=" + self.teachername + "]").click()

    def writeContent(self, content, oldcontent):
        '''填写短信发送内容'''
        smsInfo = content + time.strftime('%Y%m%d%H%M%S')
        self.dr.find_element_by_id(self.sms_content_id).clear()
        self.dr.find_element_by_id(self.sms_content_id).send_keys(oldcontent + smsInfo)
        return oldcontent + smsInfo

    def checkSmsIsSuccess(self, smsInfo, studentname):
        '''查询之前短信是否真实发送成功'''
        isSuccess = False
        self.dr.switch_to.parent_frame()
        self.moduopr.openMoudleAndIn(self.smsNavigation_class, self.sms_mysend_url)
        self.dr.find_element_by_xpath(self.sms_mysend_tab_mysend_xpath).click()
        self.dr.find_element_by_id(self.sms_mysend_keyword_id).send_keys(smsInfo)
        self.dr.find_elements_by_class_name(self.sms_mysend_btn_class)[0].click()
        smsReceiveInfoList = self.dr.find_elements_by_class_name(self.sms_mysend_receive_btn)
        if len(smsReceiveInfoList) > 0:
            smsReceiveInfoList[0].click()
            self.dr.switch_to.frame(self.sms_mysend_receiver_frame)
            receiverstudentnames = self.dr.find_elements_by_xpath(
                self.sms_mysend_receiver_frame_username)
            if receiverstudentnames[1].text == studentname:
                isSuccess = True
        return isSuccess

    def tacherSendQuery(self, name, sendText, timer=None):
        """
        教职工发送的模块，跟进发送人姓名+短息内容+时间来查询
        :param name:送人姓名
        :param sendText:短信内容
        :param timer:None默认为today，future=未来20天，其他输入传入时间
        :return:
        """
        dr = self.dr
        # 输入发送人姓名+短信内容+时间（今天）
        dr.find_element_by_class_name(self.sms_teachersend_chosen_class).click()
        dr.find_element_by_class_name(self.sms_teachersend_chosen_teacherinput_class).send_keys(name)
        teachers = dr.find_elements_by_xpath(self.sms_teachersend_chosen_teachernamelist_xpath)
        for teacher in teachers:
            if name == teacher.text:
                teacher.click()
        self.clearAndSendKeyForText(dr.find_element_by_id(self.sms_teachersend_keyword_id), sendText)
        dr.find_element_by_id(self.sms_teachersend_time_id).click()
        if timer == None:
            dr.find_element_by_xpath(self.sms_teachersend_time_today_xpath).click()
        elif timer == "future":
            futuretime = time.strftime('%Y-%m-%d', time.localtime(time.time() + 86400)) + " 至 " + time.strftime(
                '%Y-%m-%d', time.localtime(time.time() + 86400 * 20))
            # afterTomorrowTime = (datetime.datetime.now() + datetime.timedelta(days=2)).strftime('%Y-%m-%d %H:%M:%S')
            self.clearAndSendKeyForText(dr.find_element_by_id(self.sms_teachersend_time_id),futuretime)
        else:
            dr.find_element_by_id(self.sms_teachersend_time_id).send_keys(timer)
        dr.find_element_by_css_selector(self.sms_teachersend_selectbtn_css).click()
